package com.aliyun.flashsale.server.service;

import com.aliyun.commons.model.Result;
import com.aliyun.commons.service.CacheService;
import com.aliyun.flashsale.client.model.FlashSaleProductDTO;
import com.aliyun.flashsale.client.service.FlashSaleProductService;
import com.aliyun.flashsale.server.dao.entity.FlashSaleProductDO;
import com.aliyun.flashsale.server.dao.mapper.FlashSaleProductMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 秒杀商品服务
 *
 * 
 * @date 2024/11/27
 */
@DubboService
public class FlashSaleProductServiceImpl implements FlashSaleProductService {

    private static final String FLASH_SALE_PRODUCT_CACHE_KEY = "FLASH_SALE_PRODUCT_";

    @Autowired
    private FlashSaleProductMapper flashSaleProductMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public Result<FlashSaleProductDTO> getFlashSaleProduct(long flashSaleProductId) {
        String key = buildCacheKey(flashSaleProductId);
        FlashSaleProductDO flashSaleProductDO = cacheService.getValue(key, FlashSaleProductDO.class);
        if (flashSaleProductDO == null) {
            flashSaleProductDO = flashSaleProductMapper.selectById(flashSaleProductId);
            if (flashSaleProductDO != null) {
                // 永久缓存
                cacheService.setValue(key, flashSaleProductDO, 0);
            }
        }
        return Result.success(toProductDTO(flashSaleProductDO));
    }

    @Override
    public Result<Void> resetCache(Long flashSaleProductId) {
        cacheService.deleteKey(buildCacheKey(flashSaleProductId));
        getFlashSaleProduct(flashSaleProductId);
        return Result.success(null);
    }

    /**
     * 构建缓存键
     *
     * @param flashSaleProductId 限时抢购商品 ID
     * @return {@link String }
     */
    private String buildCacheKey(long flashSaleProductId) {
        return FLASH_SALE_PRODUCT_CACHE_KEY + flashSaleProductId;
    }

    /**
     * 转换商品 DTO
     *
     * @param flashSaleProductDO 商品实体
     * @return {@link FlashSaleProductDTO }
     */
    private FlashSaleProductDTO toProductDTO(FlashSaleProductDO flashSaleProductDO) {
        if (flashSaleProductDO == null) {
            return null;
        }
        FlashSaleProductDTO flashSaleProductDTO = new FlashSaleProductDTO();
        flashSaleProductDTO.setId(flashSaleProductDO.getId());
        flashSaleProductDTO.setProductId(flashSaleProductDO.getProductId());
        flashSaleProductDTO.setGmtCreate(flashSaleProductDO.getGmtCreate());
        flashSaleProductDTO.setFlashSalePrice(flashSaleProductDO.getFlashSalePrice());
        flashSaleProductDTO.setStartTime(flashSaleProductDO.getStartTime());
        flashSaleProductDTO.setEndTime(flashSaleProductDO.getEndTime());
        return flashSaleProductDTO;
    }
}